const Koa = require('koa');
const app = new Koa();
const path = require('path');
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
//const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const koaStatic = require('koa-static');
const koajwt = require('koa-jwt');
const koaBody = require('koa-body');

const index = require('./routes/index');

// error handler
onerror(app);

// middlewares
// app.use(
//   bodyparser({
//     enableTypes: ['json', 'form', 'text'],
//   })
// );
app.use(koaBody({
  multipart: true, // 支持文件上传
  formidable: {
    //uploadDir: path.join(__dirname, 'public/upload/'), // 设置文件上传目录
    maxFieldsSize: 10 * 1024 * 1024, // 文件上传大小
  }
}));
app.use(json());
app.use(logger());
app.use(koaStatic(__dirname + '/public'));

app.use(
  views(__dirname + '/views', {
    extension: 'pug',
  })
);

// 错误处理
app.use(async (ctx, next) => {
  return next().catch((err) => {
    if (err.status === 401) {
      ctx.status = 401;
      ctx.body = 'Protected resource, use Authorization header to get access\n';
    } else {
      throw err;
    }
  });
});
app.use(
  koajwt({ secret: 'mb-token' }).unless({
    path: ['/captchaImage', '/login'],
  })
);

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// routes
app.use(index.routes(), index.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx);
});

module.exports = app;
